package com.bxd.baodan.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.j256.ormlite.dao.Dao;
import com.bxd.baodan.R;
import com.bxd.baodan.activity.AnswerDetailActivity;
import com.bxd.baodan.activity.MsgActivity;
import com.bxd.baodan.activity.QuestionDetailActivity;
import com.bxd.baodan.adapter.CommonAdapter;
import com.bxd.baodan.adapter.ViewHolder;
import com.bxd.baodan.app.Constant;
import com.bxd.baodan.db.DBHelper;
import com.bxd.baodan.item.MessageItem;
import com.bxd.baodan.widget.MyListView;
import com.tencent.qcloud.timchat.utils.PushUtil;
import com.tencent.qcloud.timchat.utils.TimeUtil;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


/**
 * 会话列表界面
 */
public class MsgQuestionFragment extends BaseFragment  {

    Dao<MessageItem, ?> dao;
    private View view;
    private MyListView adviserLv;
    public CommonAdapter<MessageItem> adviserMsgAdapter;
    boolean isPrepared = false;
    View emptyView;
    private List<MessageItem> adviserMsgList = new ArrayList<>();
    public String[] msgType = {Constant.MSG_NEW_ANSWER + "", Constant.MSG_NEW_ANSWER_ADD + ""};


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_qes_msg, container, false);
            adviserLv = (MyListView) view.findViewById(R.id.list_adviser);
            emptyView = view.findViewById(R.id.empty_view);
            try {
                dao = DBHelper.getInstance(context).getDao(MessageItem.class);
            } catch (SQLException e) {
                e.printStackTrace();
            }

            setAnswerMsgAdapter();
            adviserLv.setAdapter(adviserMsgAdapter);

        }

        refresh();
        return view;

    }

    public void getDbData() {
        try {
            if (dao == null) {
                // FIXME: 18/1/25 点击全部已读,第三个还没有初始化,会崩溃
                return;
            }
            adviserMsgList.clear();
            List<MessageItem> daoList = dao.queryBuilder().orderBy("time", false).where().
                    in("type", msgType).query();
            adviserMsgList.addAll(daoList);
            adviserMsgAdapter.notifyDataSetChanged();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private void setAnswerMsgAdapter() {
        adviserMsgAdapter = new CommonAdapter<MessageItem>(getActivity(), adviserMsgList, R.layout.planer_msg_item) {
            @Override
            public void convert(final ViewHolder holder, final MessageItem item) {
                TextView tvName = (TextView) holder.getView(R.id.name);
                TextView time = (TextView) holder.getView(R.id.message_time);
                TextView unread = (TextView) holder.getView(R.id.unread_num);
                TextView see = (TextView) holder.getView(R.id.see);


                time.setText(TimeUtil.getTime(item.getTime()));



                tvName.setText(item.getTitle());


                //点击查看,置为已读
                see.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // TODO: 2017/11/16 已读
                        Dao<MessageItem, ?> dao;
                        try {
                            dao = DBHelper.getInstance(getActivity()).getDao(MessageItem.class);
                            item.setIsread(true);
                            dao.createOrUpdate(item);
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                        adviserMsgList.get(holder.getPosition()).setIsread(true);
                        adviserMsgAdapter.notifyDataSetChanged();
                      //  setRedIcon();
                        if (item.getType() == Constant.MSG_NEW_ANSWER) {
                            openActivity(QuestionDetailActivity.class, new String[]{"qid"}, new String[]{item.getQid() + ""});
                        } else  if (item.getType() == Constant.MSG_NEW_ANSWER_ADD) {
                            openActivity(AnswerDetailActivity.class, new String[]{"qid","qaid"}, new String[]{item.getQid() + "",item.getAid()+""});
                        }
                    }
                });


                if (item.isIsread()) {
                    unread.setBackgroundColor(context.getResources().getColor(R.color.text_gray));
                    tvName.setTextColor(context.getResources().getColor(R.color.text_gray));
                } else {
                    unread.setBackgroundColor(context.getResources().getColor(R.color.green_lab));
                    tvName.setTextColor(context.getResources().getColor(R.color.black));
                }
            }
        };
    }









    /**
     * 刷新
     */


    public void setRedIcon() {

        long answerUnRead = 0;

        try {
            answerUnRead = dao.queryBuilder().where().
                    eq("isread", false).and().in("type", msgType).countOf();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        boolean haveUnread =  answerUnRead > 0;
        ((MsgActivity) context).setQesRed(haveUnread);

    }


    public void refresh() {
    //    setRedIcon();
        getDbData();
        // TODO: 2017/4/5 添加提问
        // &&
        if (adviserMsgList.size() > 0) {
            emptyView.setVisibility(View.GONE);
        } else {
            emptyView.setVisibility(View.VISIBLE);
        }




    }











    @Override
    public void onDestroyView() {
        super.onDestroyView();
        isPrepared = false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();


    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if (isPrepared && getUserVisibleHint()) {
            refresh();
            PushUtil.getInstance().reset();
        }

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);

        if (!hidden) {

            if (!hidden) {

                refresh();
            }
        }


    }


}
